package wind.test.client;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.util.StringUtils;
import wind.test.model.WeatherSimple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class WeatherClient {


    @Value("${weather.url1}")
    private String weatherInfoUrl1;

    @Value("${weather.url1}")
    private String weatherInfoUrl2;

    private static final Logger logger = LoggerFactory.getLogger(WeatherClient.class);

    public WeatherSimple getWeatherSimpleInfo(String position) {
        if(StringUtils.isEmpty(position)) {
            return new WeatherSimple();
        }
        WeatherSimple result = new WeatherSimple();
        JSONObject parse = new JSONObject();
        // 双url  url1获取异常  从url2获取   多数据源可配置在配置中心或配置文件中
        try {
            String url1 = String.format(weatherInfoUrl1, position);
            String weatherInfoStr = HttpUtil.get(url1);

            parse = JSONUtil.parseObj(weatherInfoStr);
        } catch (RuntimeException e) {
            logger.error("get weather info error from url1, change to url2", e);
            try {
                String url2 = String.format(weatherInfoUrl2, position);

                String weatherInfoStr = HttpUtil.get(url2);
                parse = JSONUtil.parseObj(weatherInfoStr);
            } catch (RuntimeException ex) {
                logger.error("get weather info error", ex);
            }

        }
        String status = parse.getStr("status");

        if ("ok".equals(status)) {
            JSONObject resultObj = parse.getJSONObject("result");
            if (null != resultObj) {
                JSONObject realtimeObj = resultObj.getJSONObject("realtime");
                if (null != realtimeObj && "ok".equals(realtimeObj.getStr("status"))) {
                    result.setSkycon(realtimeObj.getStr("skycon", ""));

                    JSONObject windObj = realtimeObj.getJSONObject("wind");
                    BigDecimal speed = windObj.getBigDecimal("speed", new BigDecimal(0));
                    BigDecimal direction = windObj.getBigDecimal("direction", new BigDecimal(0));

                    WeatherSimple.WindInfo windInfo = new WeatherSimple.WindInfo();
                    windInfo.setSpeed(speed);
                    windInfo.setDirection(direction);

                    result.setWindInfo(windInfo);

                    BigDecimal temperature = realtimeObj.getBigDecimal("temperature", new BigDecimal(0));
                    result.setTemperature(temperature);
                    return result;
                }
            }
        }
        return new WeatherSimple();

    }
}
